﻿/* 
 * Copyright (c) 2009 Intel Corporation
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * -- Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * -- Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * -- Neither the name of the Intel Corporation nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE INTEL OR ITS
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * Contributor: Nathan Letwory
 */

using System;
using System.Runtime.InteropServices;

namespace VerseSharp
{

    //[StructLayout(LayoutKind.Explicit)]
    public struct ParamValue
    {
        public int vint8; // note that this should be encoded as one byte!
        public Int16 vint16;
        public Int32 vint32;
        public uint vuint8; // note that this should be encoded as one byte!
        public UInt16 vuint16;
        public UInt32 vuint32;
        public float vreal32;
        public double vreal64;
        public string vstring;
        public uint vnode;
        public UInt16 vlayer;
    }
    public class MethodParameter
    {
        public ParamType Type;
        public string Name;
        public ParamValue Value;
    }

    public delegate void ObjectMethodCreateCallback(ObjectMethodCreateCommand command);
    public delegate void ObjectMethodDestroyCallback(ObjectMethodCreateCommand command);

    public class ObjectMethodCreateCommand : IVerseCommand
    {
        public CommandID ID { get { return CommandID.ObjectMethodCreate; } }
        public uint NodeID;
        /// <summary>
        /// ID of the method group.
        /// </summary>
        public ushort GroupID;
        public ushort MethodID;
        /// <summary>
        /// Name of the method group. Maximum 16 bytes long. Set to null if the method group is destroyed.
        /// </summary>
        public string Name;
        public byte ParamCount;
        public MethodParameter[] Parameters;
        public bool Destroy;

        // Note that the specs don't explain everything (explicitely).
        // The ParamCount length is byte.MaxValue if object_method_destroy is intended, so is Name "" or null.
        // While this would give possibly 254 parameters of 16byte strings, the verse package max length still
        // counts: 1500 bytes. This means that you lose already potentially 4+2+2+512+1 bytes before parameter
        // information is encoded. This you should keep in mind when creating parameters: you need 1 byte to encode
        // the type, and at least 2 bytes (one char + null, up to 16 excluding null char) for name encoding.
        // The reference implementation fails to do proper checking of name lengths, so there is a potential
        // risc there.
        public void Deserialize(byte[] source, ref int pos)
        {
            NodeID = Utils.GetUInt32(source, ref pos);
            GroupID = Utils.GetUInt16(source, ref pos);
            MethodID = Utils.GetUInt16(source, ref pos);
            Name = Utils.GetString(source, 512, ref pos);
            ParamCount = source[pos++];
            if (String.IsNullOrEmpty(Name) && ParamCount == byte.MaxValue)
            {
                Destroy = true;
            }
            if (ParamCount > 0 && ParamCount < byte.MaxValue)
            {
                Parameters = new MethodParameter[ParamCount];
                for (int i = 0; i < ParamCount; i++)
                {
                    Parameters[0] = new MethodParameter();
                    Parameters[0].Type = (ParamType)source[pos++];
                    Parameters[0].Name = Utils.GetString(source, 16, ref pos); // note that here verse reference implementation doesn't check for name max length 16, but only up until the maximum verse packet size of 1500. We do this for now, but we might have to change that.
                }
            }
        }

        public void Serialize(byte[] destination, ref int pos)
        {
            Utils.PutUInt32(destination, ref pos, NodeID);
            Utils.PutUInt16(destination, ref pos, GroupID);
            Utils.PutUInt16(destination, ref pos, MethodID);
            if ((Name == null && ParamCount == byte.MaxValue) || Destroy == true)
            {
                destination[pos++] = 0;
                destination[pos++] = byte.MaxValue;
            }
            else
            {
                Utils.PutString(destination, Name, 512, ref pos);
                destination[pos++] = ParamCount;
                // TODO add max length check
                for (int i = 0; i < ParamCount; i++)
                {
                    destination[pos++] = (byte)Parameters[i].Type;
                    Utils.PutString(destination, Parameters[i].Name, 16, ref pos);
                }
            }
        }
    }
}
